// src/utils/toast.js
import Vue from 'vue';
import ToastComponent from '@/components/common/Toast/index.vue';

let instance = null;

function getInstance() {
  if (!instance) {
    const ToastConstructor = Vue.extend(ToastComponent);
    instance = new ToastConstructor().$mount(document.createElement('div'));
    document.body.appendChild(instance.$el);
  }
  return instance;
}

function showToast(options) {
  const instance = getInstance();

  // 处理字符串调用
  if (typeof options === 'string') {
    options = { message: options };
  }

  // 合并默认值
  const config = {
    message: options.message || '提示',
    type: options.type || 'info',
    duration: options.duration || 3000,
  };

  // ✅ 确保调用 show 方法触发更新
  instance.show(config);

  return showToast;
}

// 快捷方法
['success', 'error', 'warning', 'info'].forEach(type => {
  showToast[type] = (message, duration) => {
    return showToast({
      message,
      type,
      duration,
    });
  };
});

export default showToast;
